import { Component } from '@angular/core';
import { NavController, NavParams , ToastController } from 'ionic-angular';
import { Storage } from '@ionic/storage';

/**
 * Generated class for the RegisterPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@Component({
  selector: 'page-register',
  templateUrl: 'register.html',
})
export class RegisterPage {

  public user : string;
  public pwd : string;
  constructor(
    public navCtrl: NavController, 
    public navParams: NavParams,
    private toast : ToastController,
    private storage : Storage
  ) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad RegisterPage');
  }

  public regist(){
    if(this.user.trim().length == 0){
      this.emitTost('用户名不能为空');
      return;
    }
    if(this.pwd.trim().length == 0){
      this.emitTost('密码不能为空');
      return;
    }
    this.storage.get(this.user.trim()).then(val=>{
      if(!val){
        this.storage.set(this.user.trim(),this.pwd.trim()).then(()=>{
          this.emitTost('注册成功,请登录');
          this.navCtrl.pop();
        });
      }else{
        this.emitTost('用户名已存在');
      }
    })

  }
  
  private emitTost (message){
    let toast = this.toast.create({
        message : message,
        duration : 2000,
        position : 'top'
    });
    toast.present();
  }

}
